package com.css.fxfzypg.modules.baseData.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.common.utils.CheckObjFields;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.dto.HouseDTO;
import com.css.fxfzypg.modules.baseData.entity.HouseEntity;
import com.css.fxfzypg.modules.baseData.queryParams.HouseQueryParams;
import com.css.fxfzypg.modules.baseData.repository.HouseRepository;
import com.css.fxfzypg.modules.baseData.service.HouseService;
import com.css.fxfzypg.modules.baseData.vo.HouseVO;
import com.css.fxfzypg.util.PlatformDateUtils;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author y1fan
 * @create 2022-08-12 12:07
 */
@Slf4j
@Service
public class HouseServiceImpl implements HouseService {


    @Resource
    private HouseRepository houseRepository;

    @Autowired
    private SysAreaService sysAreaService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public HouseEntity getHouseById(String id) {
        return houseRepository.getHouseById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHouse(HouseDTO houseDTO) {
        houseDTO.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        houseDTO.setUpdateUser(PlatformSessionContext.getUserID());
        houseRepository.updateHouse(houseDTO);
    }


    @Override
    public Map<String, Object> getAllHouseByParams(HouseQueryParams queryParams, int curPage, int pageSize) {
        Map<String, Object> page = houseRepository.getAllHouseByParams(queryParams, curPage, pageSize);
        return page;
    }

    @Override
    public void deleteHouse(List<String> list) {
        houseRepository.deleteHouse(list);
    }


    @Override
    public String importExcel(MultipartFile file) {
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setTitleRows(0);
            params.setHeadRows(2);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HouseVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HouseVO.class, params);

            List<HouseVO> list = result.getList();
            if (PlatformObjectUtils.isNotEmpty(list)) {
                for (HouseVO item : list) {
                    HouseEntity houseEntity = houseRepository.findPeoByProAndCityAndPre(item.getProvince(), item.getCity(), item.getPrefecture());
                    if (PlatformObjectUtils.isNotEmpty(houseEntity)) {
                        BeanUtils.copyProperties(item, houseEntity);
                        houseEntity.setUpdateUser(PlatformSessionContext.getUserID());
                        houseEntity.setUpdateTime(new Date());
                        houseRepository.importExcel(houseEntity);
                    } else {
                        HouseEntity houseEntity1 = new HouseEntity();
                        BeanUtils.copyProperties(item, houseEntity1);
                        String divisionIds = "";

                        //判断省市县的名称是否符合规范
                        divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(item.getProvince(), "utf-8"),
                                URLEncoder.encode(item.getCity(), "utf-8"),
                                URLEncoder.encode(item.getPrefecture(), "utf-8"));

                        if (StringUtils.isBlank(divisionIds) || divisionIds.split("_").length < 3) {
                            return "导入失败，请检查" + item.getProvince() + "," + item.getCity() + "," + item.getPrefecture() + "数据正确性";
                        }
                        String[] split = divisionIds.split("_");
                        houseEntity1.setProvinceId(split[0]);
                        houseEntity1.setCityId(split[1]);
                        houseEntity1.setPrefectureId(split[2]);
                        houseEntity1.setIsDelete(YNEnum.N.toString());
                        houseEntity1.setCreateUser(PlatformSessionContext.getUserID());
                        houseEntity1.setCreateTime(new Date());
                        houseEntity1.setHousePriceId(UUIDGenerator.getUUID());
                        houseEntity1.setProvinceCode(areaIdCodeMap.get(houseEntity1.getProvinceId()));
                        houseEntity1.setCityCode(areaIdCodeMap.get(houseEntity1.getCityId()));
                        houseEntity1.setPrefectureCode(areaIdCodeMap.get(houseEntity1.getPrefectureId()));
                        houseRepository.save(houseEntity1);
                    }
                }
                returnMsg.append("成功导入" + (result.getList().size()) + "条<br/>");
            }

            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HouseVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HouseVO peoVO = iterator.next();
                    HouseEntity HouseEntity = new HouseEntity();
                    BeanUtils.copyProperties(peoVO, HouseEntity);
                    if (CheckObjFields.isAllFieldNull(HouseEntity)) {
                        continue;
                    }
                    int i = peoVO.getRowNum() + params.getHeadRows() - 1;

                    returnMsg.append("第" + i + "行" + peoVO.getErrorMsg() + "<br/>");
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public HouseEntity getHouse(String province, String city, String prefecture) {
        return houseRepository.getHouse(province, city, prefecture);
    }

    @Override
    public Integer countByCounty(String province, String city, String county) {
        return houseRepository.countByCounty(province, city, county);
    }

    @Override
    public Integer countByCity(String province, String city) {
        return houseRepository.countByCity(province, city);
    }

    @Override
    public Integer countByProvince(String name) {
        return houseRepository.countByProvince(name);
    }

    @Override
    public Integer countByProvinceAndYear(String provinceName, String taskYear) {
        return houseRepository.countByProvinceAndYear(provinceName, taskYear);
    }
}
